package com.personal.service.Impl;

import cn.hutool.crypto.asymmetric.Sign;
import com.personal.enums.SignEnum;
import com.personal.enums.UserEnum;
import com.personal.exception.ExceptionUtils;
import com.personal.mapper.DynamicMapper;
import com.personal.mapper.GoldCoinMapper;
import com.personal.mapper.UserSignMapper;
import com.personal.pojo.GoldCoin;
import com.personal.service.PersonalCenterService;
import com.personal.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

@Service
@Slf4j
public class PersonalCenterServiceImpl implements PersonalCenterService {

    @Autowired
    private UserSignMapper userSignMapper;

    @Autowired
    private GoldCoinMapper goldCoinMapper;

    @Autowired
    private DynamicMapper dynamicMapper;

    /**
     * 签到
     * @param userId
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Result sign(Integer userId) {
        log.info("签到接口");
        if (userId <= 0 || userId == null) {
            ExceptionUtils.error(UserEnum.USER_ID_IS_ERROR);
        }
        //判断用户今日是否签到过了
        int count = userSignMapper.queryUserSignToday(userId);
        if (count != 0){
            ExceptionUtils.error(SignEnum.USER_SIGN_SUCCESSED);
        }
        //可以签到
        int flag = userSignMapper.sign(userId,"签到成功，获得1金币");
        if (flag != 1) {
            ExceptionUtils.error(SignEnum.USER_SIGN_FAILED);
        }
        //签到成功后增加进用户账户
        //先查询用户账户信息
        HashMap userAccount = getUserAccount(userId);
        goldCoinMapper.updateCoin(userId, (int)userAccount.get("goldCoinBalance") + 1);

        //放入动态中进行轮播
        dynamicMapper.add(userId, "签到成功，获得了1金币");

        return Result.success();
    }

    /**
     * 查询用户账户信息
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public HashMap getUserAccount(int userId){
        log.info("查询用户账户信息");
        if (userId <= 0) {
            ExceptionUtils.error(UserEnum.USER_ID_IS_ERROR);
        }
        HashMap<String, Integer> map = new HashMap<>();
        GoldCoin goldCoin = goldCoinMapper.getUserAccount(userId);
        if (goldCoin == null){
            ExceptionUtils.error(SignEnum.QUERY_USER_INFO_FAILED);
        }
        map.put("userId", goldCoin.getUserId());
        map.put("goldCoinBalance", goldCoin.getGoldCoinBalance());
        map.put("goldCoinTotal", goldCoin.getGoldCoinTotal());
        map.put("commissionTotal", goldCoin.getCommissionTotal());

        return map;
    }
}
